package com.zzyl.nursing.service.impl;

import java.sql.Wrapper;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住信息Service业务层处理
 *
 * @author lzl
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1、检验老人是否已入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1)
        );
        if (elder != null) {
            throw new RuntimeException("该老人已入住");
        }
        //2、更新床位状态为入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3、新增或更新老人
        elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);
        //新增合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        //4、新增签约办理
        insertContract(contractNo, elder, dto);
        //5、新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);
        //6、新增入住配置
        insertCheckInConfig(checkIn.getId(), dto);
    }

    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, newElder);
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());
        newElder.setStatus(1);
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, newElder.getIdCardNo())
                .ne(Elder::getStatus, 1)
        );
        if (oldElder != null) {
            //更新
            elderMapper.updateById(newElder);
        } else {
            //新增
            elderMapper.insert(newElder);
        }
        return newElder;
    }

    @Override
    public CheckInDetailVo findCheckInById(Long id) {
        //查询入住信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1、查询老人信息
        CheckInElderVo checkInElderVo = elderMapper.findByCheckInId(id);
        String idCardNo = checkInElderVo.getIdCardNo();
        String birthday = idCardNo.substring(6, 14);
        // 解析出生日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthday, formatter);
        LocalDate now = LocalDate.now();
        checkInElderVo.setAge(Period.between(birthDate, now).getYears());
        //2、转换家属列表
        Long elderId = checkInElderVo.getId();
        String family = checkInMapper.findFamilyByElderId(elderId);
        if (family != null) {
            checkInDetailVo.setElderFamilyVoList(JSON.parseArray(family, ElderFamilyVo.class));
        }
        //3、查询入住配置
        CheckInConfigVo checkInConfigVo = checkInConfigMapper.findByCheckInId(id);
        //4、查询合同
        Contract contract = contractMapper.findByElderId(elderId);
        //5、整合数据返回
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
